from flask import Flask, request
import json
from handle_module import SyncHanleWithReq, OldSyncHanleWithReqForGroup, OldSyncHanleWithReqForNumber
import logging
import http_log
# !/usr/bin/env python
import time, platform
import os
import sys

app = Flask(__name__)


@app.route('/nothing', methods=['POST', 'GET'])
def nothing_arg_search():
    logging.info(request.headers)
    info = request.stream.read().decode(encoding='UTF-8')

    logging.info(info)

    response_dict = {
        "returnCode": 0,
        "returnMessage": "succ",
    }

    logging.info(response_dict)
    return json.dumps(response_dict)

@app.route('/', methods=['POST', 'GET'])
def ivr_arg_search():
    logging.info(request.headers)
    info = request.stream.read().decode(encoding='UTF-8')

    logging.info(info)

    rsp = SyncHanleWithReq(info)
    logging.info(rsp)
    return rsp


@app.route('/oldGroup', methods=['POST', 'GET'])
def old_ivr_group_arg_search():
    logging.info(request.headers)
    info = request.stream.read().decode(encoding='UTF-8')

    logging.info(info)

    #	rsp = OldSyncHanleWithReqForGroup(info)
    rsp = OldSyncHanleWithReqForNumber(info)

    logging.info(rsp)
    return rsp


@app.route('/oldNumber', methods=['POST', 'GET'])
def old_ivr_number_arg_search():
    logging.info(request.headers)
    info = request.stream.read().decode(encoding='UTF-8')

    logging.info(info)

    rsp = OldSyncHanleWithReqForNumber(info)
    logging.info(rsp)
    return rsp


def funzioneDemo():
    # 这是具体业务函数示例
    app.run(host='10.206.0.5', port=8777, debug=True)


def createDaemon():
    # fork进程
    try:
        if os.fork() > 0: os._exit(0)
    except OSError as error:
        print('fork #1 failed: %d (%s)' % (error.errno, error.strerror))
        os._exit(1)
    os.setsid()
    os.umask(0)
    try:
        pid = os.fork()
        if pid > 0:
            print('Daemon PID %d' % pid)
            os._exit(0)
    except OSError as error:
        print('fork #2 failed: %d (%s)' % (error.errno, error.strerror))
        os._exit(1)

    funzioneDemo()  # function demo


if __name__ == '__main__':
    if platform.system() == "Linux":
        createDaemon()
    else:
        os._exit(0)
